package com.dianneng.show.fragment;


import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.OrientationHelper;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.TextView;

import com.blankj.utilcode.util.ToastUtils;
import com.blankj.utilcode.util.Utils;
import com.dianneng.show.R;
import com.dianneng.show.adapter.SNInfoAdapter;
import com.dianneng.show.base.BaseFragment;
import com.dianneng.show.http.RetrofitHelper;
import com.dianneng.show.model.DayInfo;
import com.dianneng.show.model.MonthInfo;
import com.dianneng.show.util.ACache;
import com.dianneng.show.util.Constant;
import com.dianneng.show.util.DateUtil;
import com.dianneng.show.widget.DayValueFormatter;
import com.dianneng.show.widget.XYMarkerView;
import com.dianneng.show.widget.YValueFormatter;
import com.github.mikephil.charting.charts.BarChart;
import com.github.mikephil.charting.components.Legend;
import com.github.mikephil.charting.components.LimitLine;
import com.github.mikephil.charting.components.XAxis;
import com.github.mikephil.charting.components.YAxis;
import com.github.mikephil.charting.data.BarData;
import com.github.mikephil.charting.data.BarDataSet;
import com.github.mikephil.charting.data.BarEntry;
import com.github.mikephil.charting.data.Entry;
import com.github.mikephil.charting.formatter.ValueFormatter;
import com.github.mikephil.charting.highlight.Highlight;
import com.github.mikephil.charting.interfaces.datasets.IBarDataSet;
import com.github.mikephil.charting.listener.OnChartValueSelectedListener;
import com.xingliuhua.libnetstatelayout.view.INetErrorView;
import com.xingliuhua.libnetstatelayout.view.NetStateLayout;

import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.functions.Consumer;
import io.reactivex.schedulers.Schedulers;

public class InfoFragment extends BaseFragment {

    @BindView(R.id.nt_total)
    NetStateLayout ntTotal;
    @BindView(R.id.bc_dianliang)
    BarChart bcDianliang;
    @BindView(R.id.sw_content)
    SwipeRefreshLayout swContent;
    @BindView(R.id.rv_sn)
    RecyclerView rvSn;
    SNInfoAdapter snInfoAdapter;
    List<DayInfo.DataBean> dayDatas = new ArrayList<>();
    List<MonthInfo.DataBean> monthDatas = new ArrayList<>();
    @BindView(R.id.tv_date)
    TextView tvDate;
    @BindView(R.id.tv_haodian)
    TextView tvHaodian;

    private DateUtil.DateInfo dateInfo;

    @Override
    protected int setLayoutResourceID() {
        return R.layout.fragment_info;
    }

    @Override
    protected void setUpView() {
        initBarChart();
        swContent.setColorSchemeResources(R.color.colorPrimaryDark, R.color.colorPrimary, R.color.colorAccent);
        swContent.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                swContent.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        setUpData();
                    }
                }, 1000);
            }
        });

        ntTotal.setContentState(NetStateLayout.CONTENT_STATE_SHOW_LOADING);
        ntTotal.setOnRetryClickListener(new INetErrorView.OnRetryClickListener() {
            @Override
            public void onRetryClicked() {
                ntTotal.setContentState(NetStateLayout.CONTENT_STATE_SHOW_LOADING);
                setUpData();
            }
        });

        LinearLayoutManager layoutManager = new LinearLayoutManager(getActivity());
        //设置布局管理器
        rvSn.setLayoutManager(layoutManager);
        //设置为垂直布局，这也是默认的
        layoutManager.setOrientation(OrientationHelper.VERTICAL);

        snInfoAdapter = new SNInfoAdapter(dayDatas, getActivity());
        rvSn.setAdapter(snInfoAdapter);

        dateInfo = DateUtil.getCurrentDate();
    }

    @Override
    protected void setUpData() {
        swContent.setRefreshing(true);
        tvDate.setText(dateInfo.getYear()+"年"+dateInfo.getMonth()+"月");
        getMonthData(dateInfo.getYear() + "", dateInfo.getMonth() + "");
    }


    /**
     * 初始化柱形图控件属性
     */
    private void initBarChart() {
        // 设置x轴的LimitLine，index是从0开始的
        bcDianliang.setOnChartValueSelectedListener(new OnChartValueSelectedListener() {
            @Override
            public void onValueSelected(Entry e, Highlight h) {
                bcDianliang.getXAxis().removeAllLimitLines();
                LimitLine xLimitLine = new LimitLine(e.getX(), "");
                xLimitLine.setLineColor(getResources().getColor(R.color.colorPrimary));
                xLimitLine.setTextColor(getResources().getColor(R.color.colorPrimary));
                bcDianliang.getXAxis().addLimitLine(xLimitLine);

                mLoadingDialog.setLoadingText("获取数据中...").show();
                dateInfo.setDay((int)e.getX());
                getDayData(dateInfo.getYear() + "", dateInfo.getMonth() + "", dateInfo.getDay()+"");
            }

            @Override
            public void onNothingSelected() {
                bcDianliang.getXAxis().removeAllLimitLines();
            }
        });
        bcDianliang.getDescription().setEnabled(false);
        bcDianliang.setDoubleTapToZoomEnabled(false);
        bcDianliang.setScaleEnabled(false);
        bcDianliang.setMaxVisibleValueCount(32);
        bcDianliang.setDrawValueAboveBar(true);


        ValueFormatter dayValueFormatter = new DayValueFormatter();
        XAxis xAxis = bcDianliang.getXAxis();
        xAxis.setPosition(XAxis.XAxisPosition.BOTTOM);
        xAxis.setDrawGridLines(false);
        xAxis.setGranularity(1f);
        xAxis.setLabelCount(25, false);
        xAxis.setValueFormatter(dayValueFormatter);


        //获取到图形左边的Y轴
        ValueFormatter yValueFormatter = new YValueFormatter();
        YAxis leftAxis = bcDianliang.getAxisLeft();
        leftAxis.setLabelCount(6, false);
        leftAxis.setPosition(YAxis.YAxisLabelPosition.OUTSIDE_CHART);
        leftAxis.setSpaceTop(16f);
        leftAxis.setAxisMinimum(0f);
        leftAxis.setValueFormatter(yValueFormatter);

        //获取到图形右边的Y轴，并设置为不显示
        bcDianliang.getAxisRight().setEnabled(false);

        //图例设置
        Legend legend = bcDianliang.getLegend();
        legend.setVerticalAlignment(Legend.LegendVerticalAlignment.BOTTOM);
        legend.setHorizontalAlignment(Legend.LegendHorizontalAlignment.LEFT);
        legend.setOrientation(Legend.LegendOrientation.HORIZONTAL);
        legend.setDrawInside(false);

        XYMarkerView xyMarkerView = new XYMarkerView(getActivity());
        xyMarkerView.setChartView(bcDianliang);
        bcDianliang.setMarker(xyMarkerView);
    }


    private void setBarChartData() {
        bcDianliang.getXAxis().removeAllLimitLines();
        bcDianliang.clear();

        ArrayList<BarEntry> yVals1 = new ArrayList<BarEntry>();

        //在这里设置自己的数据源,BarEntry 只接收float的参数，
        //图形横纵坐标默认为float形式，如果想展示文字形式，需要自定义适配器，
        float total=0,p=0;

        for (int i = 0; i < monthDatas.size(); i++) {
            yVals1.add(new BarEntry(i + 1, monthDatas.get(i).getEq()));
            total+=monthDatas.get(i).getEq();
        }
        p=total/31f;
        DecimalFormat df = new DecimalFormat("0.000");
        tvHaodian.setText("总耗电："+total+"kW·h\n日均："+df.format(p)+"kW·h");

        BarDataSet set1;
        set1 = new BarDataSet(yVals1, dateInfo.getYear()+"年"+dateInfo.getMonth()+"月");
        set1.setDrawIcons(false);
        set1.setColor(getResources().getColor(R.color.colorAccent));
        set1.setHighLightAlpha(255);
        set1.setHighLightColor(getResources().getColor(R.color.colorPrimary));
        set1.setHighlightEnabled(true);

        ArrayList<IBarDataSet> dataSets = new ArrayList<>();
        dataSets.add(set1);

        BarData data = new BarData(dataSets);
        data.setValueTextSize(10f);
        data.setValueTextColor(getResources().getColor(R.color.colorPrimary));
        data.setDrawValues(false);
        data.setBarWidth(0.9f);
        data.setHighlightEnabled(true);

        bcDianliang.setData(data);
        if (dateInfo.getDay()<=monthDatas.size())
            bcDianliang.highlightValue(yVals1.get(dateInfo.getDay()-1).getX(),0);
    }


    private void getDayData(String year, String month, String day) {
        disposables.add(RetrofitHelper.getHelper(getActivity()).getUserInfoService().listday(ACache.get(Utils.getApp()).getAsString(Constant.TEMP_SN), year, month, day)
                        .subscribeOn(Schedulers.io())
                        .observeOn(AndroidSchedulers.mainThread())
                        .subscribe(new Consumer<DayInfo>() {
                            @Override
                            public void accept(DayInfo info) {
                                dayDatas.clear();
                                dayDatas.add(DayInfo.setTitle());
                                for (DayInfo.DataBean dataBean : info.getData()) {
                                    dayDatas.add(DayInfo.getHandleData(dataBean));
                                }
                                snInfoAdapter.setNewData(dayDatas);
                                ntTotal.setContentState(NetStateLayout.CONTENT_STATE_HIDE);
                                swContent.setRefreshing(false);
                                mLoadingDialog.close();
                            }
                        }, new Consumer<Throwable>() {
                            @Override
                            public void accept(Throwable throwable) {
                                throwable.printStackTrace();
                                ntTotal.setContentState(NetStateLayout.CONTENT_STATE_HIDE);
                                ToastUtils.showLong("网络信号质量较差，请稍后刷新重试");
                                swContent.setRefreshing(false);
                                mLoadingDialog.close();
                            }
                        })
        );
    }

    private void getMonthData(String year, String month) {
        disposables.add(RetrofitHelper.getHelper(getActivity()).getUserInfoService().listmonth(ACache.get(Utils.getApp()).getAsString(Constant.TEMP_SN), year, month)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Consumer<MonthInfo>() {
                    @Override
                    public void accept(MonthInfo info) {
                        monthDatas.clear();
                        monthDatas = MonthInfo.getBarData(info.getData());
                        setBarChartData();
                    }
                }, new Consumer<Throwable>() {
                    @Override
                    public void accept(Throwable throwable) {
                        throwable.printStackTrace();
                        ntTotal.setContentState(NetStateLayout.CONTENT_STATE_HIDE);
                        ToastUtils.showLong("网络信号质量较差，请稍后刷新重试");
                        swContent.setRefreshing(false);
                        mLoadingDialog.close();
                    }
                })
        );
    }

    @OnClick({R.id.iv_left, R.id.iv_right})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.iv_left:
                DateUtil.DateInfo dateInfo2=DateUtil.getPreDate(dateInfo);
                if (!dateInfo2.equals(dateInfo)){
                    dateInfo=dateInfo2;
                    tvDate.setText(dateInfo.getYear()+"年"+dateInfo.getMonth()+"月");
                    mLoadingDialog.setLoadingText("获取数据中...").show();
                    getMonthData(dateInfo.getYear() + "", dateInfo.getMonth() + "");
                }
                break;
            case R.id.iv_right:
                DateUtil.DateInfo dateInfo1=DateUtil.getNextDate(dateInfo);
                if (!dateInfo1.equals(dateInfo)){
                    dateInfo=dateInfo1;
                    tvDate.setText(dateInfo.getYear()+"年"+dateInfo.getMonth()+"月");
                    mLoadingDialog.setLoadingText("获取数据中...").show();
                    getMonthData(dateInfo.getYear() + "", dateInfo.getMonth() + "");
                }
                break;
        }
    }
}
